<template>
  <div class="personal-center">
    <!-- 基础信息卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
          <el-button type="primary" @click="handleEditBaseInfo">编辑</el-button>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ userInfo.nickname }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <el-avatar :src="userInfo.avatar" />
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
        <el-descriptions-item label="手机">{{ userInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 商家信息卡片（仅商家可见） -->
    <el-card v-if="isMerchant" class="info-card">
      <template #header>
        <div class="card-header">
          <span>店铺信息</span>
          <el-button type="primary" @click="handleEditShopInfo">编辑</el-button>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="店铺名称">{{ shopInfo.shopName }}</el-descriptions-item>
        <el-descriptions-item label="店铺LOGO">
          <el-image 
            v-if="shopInfo.shopLogo" 
            :src="shopInfo.shopLogo" 
            :preview-src-list="[shopInfo.shopLogo]"
            fit="contain"
            class="shop-logo"
          />
          <span v-else>暂无</span>
        </el-descriptions-item>
        <el-descriptions-item label="店铺简介">{{ shopInfo.shopDescription || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="店铺公告">{{ shopInfo.notice || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="营业执照号">{{ shopInfo.businessLicense }}</el-descriptions-item>
        <el-descriptions-item label="法人代表">{{ shopInfo.legalPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ shopInfo.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ shopInfo.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="店铺地址">{{ shopInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="店铺等级">
          <el-rate
            v-model="shopInfo.level"
            :max="5"
            disabled
            show-score
            text-color="#ff9900"
          />
        </el-descriptions-item>
        <el-descriptions-item label="店铺评分">
          <span class="score">{{ shopInfo.score }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="营业时间">{{ shopInfo.businessHours }}</el-descriptions-item>
        <el-descriptions-item label="售后政策" :span="2">{{ shopInfo.afterSalePolicy }}</el-descriptions-item>
        <el-descriptions-item label="店铺状态">
          <el-tag :type="shopInfo.status === 1 ? 'success' : 'danger'">
            {{ shopInfo.status === 1 ? '营业中' : '已关闭' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusType(shopInfo.auditStatus)">
            {{ getAuditStatusText(shopInfo.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否推荐">
          <el-tag :type="shopInfo.isRecommend === 1 ? 'success' : 'info'">
            {{ shopInfo.isRecommend === 1 ? '已推荐' : '未推荐' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品数量">{{ shopInfo.productCount }}</el-descriptions-item>
        <el-descriptions-item label="月销量">{{ shopInfo.monthlySales }}</el-descriptions-item>
        <el-descriptions-item label="总销量">{{ shopInfo.totalSales }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ shopInfo.createTime || '暂无' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 基础信息编辑对话框 -->
    <el-dialog 
      v-model="baseInfoDialogVisible" 
      title="编辑基础信息"
      width="500px"
    >
      <el-form 
        ref="baseFormRef"
        :model="baseForm"
        :rules="baseRules"
        label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="baseForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="file => handleAvatarUpload(file.raw)"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="baseForm.avatar"
              :src="baseForm.avatar"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-button 
            v-if="baseForm.avatar" 
            type="danger" 
            link
            @click="handleDeleteAvatar"
          >
            删除头像
          </el-button>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="baseForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="baseForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="baseInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBaseSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商家信息编辑对话框 -->
    <el-dialog 
      v-if="isMerchant"
      v-model="shopInfoDialogVisible" 
      title="编辑店铺信息"
      width="60%"
    >
      <el-form 
        ref="shopFormRef"
        :model="shopForm"
        :rules="shopRules"
        label-width="120px"
        :validate-on-rule-change="false"
        :show-message="false"
      >
        <el-form-item 
          label="店铺名称" 
          prop="shopName"
        >
          <el-input 
            v-model="shopForm.shopName" 
            placeholder="请输入店铺名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="店铺LOGO">
          <el-upload
            class="logo-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleLogoChange"
            :before-upload="beforeLogoUpload"
          >
            <el-image
              v-if="shopForm.shopLogo"
              :src="shopForm.shopLogo"
              class="shop-logo"
            />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="店铺简介">
          <el-input
            v-model="shopForm.shopDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入店铺简介"
          />
        </el-form-item>
        <el-form-item label="店铺公告">
          <el-input
            v-model="shopForm.notice"
            type="textarea"
            :rows="3"
            placeholder="请输入店铺公告"
          />
        </el-form-item>
        <el-form-item label="营业执照号">
          <el-input v-model="shopForm.businessLicense" placeholder="请输入营业执照号" />
        </el-form-item>
        <el-form-item label="法人代表">
          <el-input v-model="shopForm.legalPerson" placeholder="请输入法人代表姓名" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="shopForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱">
          <el-input v-model="shopForm.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="店铺地址">
          <el-input v-model="shopForm.address" placeholder="请输入店铺地址" />
        </el-form-item>
        <el-form-item label="营业时间">
          <el-input v-model="shopForm.businessHours" placeholder="请输入营业时间，例：09:00-22:00" />
        </el-form-item>
        <el-form-item label="售后政策">
          <el-input
            v-model="shopForm.afterSalePolicy"
            type="textarea"
            :rows="3"
            placeholder="请输入售后政策"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shopInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleShopSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, uploadAvatar, deleteAvatar } from '@/api/user'
import { getShopInfo, updateShopInfo, uploadShopLogo } from '@/api/merchant'

const userStore = useUserStore()
const isMerchant = computed(() => userStore.isMerchant)
const userInfo = computed(() => userStore.userInfo || {})
const shopInfo = ref({})

// 对话框显示控制
const baseInfoDialogVisible = ref(false)
const shopInfoDialogVisible = ref(false)

// 表单引用
const baseFormRef = ref(null)
const shopFormRef = ref(null)

// 基础信息表单
const baseForm = ref({
  nickname: '',
  avatar: '',
  email: '',
  phone: ''
})

// 店铺信息表单
const shopForm = ref({
  shopName: '',
  shopLogo: '',
  shopDescription: '',
  notice: '',
  businessLicense: '',
  legalPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  businessHours: '',
  afterSalePolicy: ''
})

// 基础信息验证规则
const baseRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 店铺信息验证规则
const shopRules = {
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' }
  ]
}

// 获取商家店铺信息
const fetchShopInfo = async () => {
  if (!isMerchant.value) return
  
  try {
    const response = await getShopInfo()
    if (response.data) {
      shopInfo.value = response.data
    }
  } catch (error) {
    console.error('获取商家信息失败:', error)
    ElMessage.error('获取商家信息失败')
  }
}

// 在组件挂载时获取商家信息
onMounted(() => {
  fetchShopInfo()
})

// 处理编辑基础信息
const handleEditBaseInfo = () => {
  baseForm.value = {
    nickname: userInfo.value.nickname,
    avatar: userInfo.value.avatar,
    email: userInfo.value.email,
    phone: userInfo.value.phone
  }
  baseInfoDialogVisible.value = true
}

// 处理编辑店铺信息
const handleEditShopInfo = () => {
  shopForm.value = {
    shopName: shopInfo.value.shopName,
    shopLogo: shopInfo.value.shopLogo,
    shopDescription: shopInfo.value.shopDescription,
    notice: shopInfo.value.notice,
    businessLicense: shopInfo.value.businessLicense,
    legalPerson: shopInfo.value.legalPerson,
    contactPhone: shopInfo.value.contactPhone,
    contactEmail: shopInfo.value.contactEmail,
    address: shopInfo.value.address,
    businessHours: shopInfo.value.businessHours,
    afterSalePolicy: shopInfo.value.afterSalePolicy
  }
  shopInfoDialogVisible.value = true
}

// 处理编辑基础信息提交
const handleBaseSubmit = async () => {
  if (!baseFormRef.value) return
  await baseFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await updateUserInfo({
          nickname: baseForm.value.nickname,
          email: baseForm.value.email,
          phone: baseForm.value.phone,
          avatar: baseForm.value.avatar
        })
        if (response.data) {
          ElMessage.success('更新成功')
          baseInfoDialogVisible.value = false
          // 更新用户信息
          await userStore.fetchUserInfo()
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 处理编辑商户信息提交
const handleShopSubmit = async () => {
  try {
    const response = await updateShopInfo({
      shopName: shopForm.value.shopName,
      shopLogo: shopForm.value.shopLogo,
      shopDescription: shopForm.value.shopDescription,
      notice: shopForm.value.notice,
      businessLicense: shopForm.value.businessLicense,
      legalPerson: shopForm.value.legalPerson,
      contactPhone: shopForm.value.contactPhone,
      contactEmail: shopForm.value.contactEmail,
      address: shopForm.value.address,
      businessHours: shopForm.value.businessHours,
      afterSalePolicy: shopForm.value.afterSalePolicy
    })
    
    if (response.code === 200) {
      shopInfoDialogVisible.value = false
      await fetchShopInfo()
    }
  } catch (error) {
    console.error('更新商户信息失败:', error)
  }
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功回调
const handleAvatarUpload = async (file) => {
  try {
    const response = await uploadAvatar(file)
    if (response.data) {
      baseForm.value.avatar = response.data
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 删除头像
const handleDeleteAvatar = async () => {
  try {
    await deleteAvatar()
    baseForm.value.avatar = ''
    ElMessage.success('头像删除成功')
  } catch (error) {
    console.error('删除头像失败:', error)
    ElMessage.error('删除失败')
  }
}

// LOGO上传前校验
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// LOGO上传处理
const handleLogoChange = async (file) => {
  if (!beforeLogoUpload(file.raw)) return
  
  try {
    const response = await uploadShopLogo(file.raw)
    if (response.data) {
      shopForm.value.shopLogo = response.data
      ElMessage({
        message: 'Logo上传成功',
        type: 'success'
      })
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('Logo上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 获取审核状态类型
const getAuditStatusType = (status) => {
  const types = {
    0: 'info',    // 待审核
    1: 'success', // 已通过
    2: 'danger'   // 已拒绝
  }
  return types[status] || 'info'
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return texts[status] || '未知状态'
}
</script>

<style scoped>
.personal-center {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader,
.logo-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover,
.logo-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon,
.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar,
.shop-logo {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

:deep(.el-descriptions__cell) {
  padding: 16px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

.score {
  color: #ff9900;
  font-size: 18px;
  font-weight: bold;
}
</style>
